package com.qijian.common.utils.sync;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

public class BaseKingDee extends KingdeeSynUtils {
    protected static final String AND = " and ";

    private static final String alias = " as ";
    private static final String alias_new = "||";
    private static final String field_split = ",";

    protected List<JSONObject> getDataJson(String formId, String fieldKeys) {
        return this.getDataJson(formId, fieldKeys, "");
    }

    protected List<com.alibaba.fastjson.JSONObject> getDataJson(String formId, String[] fieldKeys, String filterString) {
        return getDataJson(formId, StringUtils.join(fieldKeys, field_split), filterString);
    }

    protected List<com.alibaba.fastjson.JSONObject> getDataJson(String formId, String fieldKeys, String filterString) {
        try {
            if (Login()) {
                String result = callData(0, formId, fieldKeys, filterString);
                if (result.contains("\"IsSuccess\":false")) {
                    System.out.println(result);
                    throw new RuntimeException();
                }
                com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(result);
                //将取值的key和value的顺序对应组成map
                List<com.alibaba.fastjson.JSONObject> data = new ArrayList<>();
                String[] fieldList = fieldKeys
                        .replaceAll(alias, alias_new)
                        .replaceAll(alias.toUpperCase(), alias_new)
                        .replaceAll(" ", "")
                        .split(",");
                for (Object a : array) {
                    com.alibaba.fastjson.JSONArray arr = (com.alibaba.fastjson.JSONArray) a;
                    com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
                    for (int i = 0; i < fieldList.length; i++) {
                        String key = fieldList[i];
                        if (key.contains(alias_new))
                            key = org.apache.commons.lang3.StringUtils.substringAfter(key, alias_new);
                        obj.put(key, arr.get(i));
                    }
                    data.add(obj);
                }
                return data;
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return Collections.emptyList();
    }


    protected List<com.alibaba.fastjson.JSONObject> getDataJson(String formId, String fieldKeys, String filterString, int start, int size) {
        try {
            if (Login()) {
                String result = callDataNew(start, size, formId, fieldKeys, filterString);
                if (result.contains("\"IsSuccess\":false")) {
                    System.out.println(result);
                    throw new RuntimeException();
                }
                com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(result);
                //将取值的key和value的顺序对应组成map
                List<com.alibaba.fastjson.JSONObject> data = new ArrayList<>();
                String[] fieldList = fieldKeys
                        .replaceAll(alias, alias_new)
                        .replaceAll(alias.toUpperCase(), alias_new)
                        .replaceAll(" ", "")
                        .split(",");
                for (Object a : array) {
                    com.alibaba.fastjson.JSONArray arr = (com.alibaba.fastjson.JSONArray) a;
                    com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
                    for (int i = 0; i < fieldList.length; i++) {
                        String key = fieldList[i];
                        if (key.contains(alias_new))
                            key = org.apache.commons.lang3.StringUtils.substringAfter(key, alias_new);
                        obj.put(key, arr.get(i));
                    }
                    data.add(obj);
                }
                return data;
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return Collections.emptyList();
    }

    protected List<Map<String, Object>> getData(String formId, String fieldKeys, String filterString) {
        try {
            if (Login()) {
                String result = callData(0, formId, fieldKeys, filterString);
                if (StrUtil.isBlank(result) || result.contains("\"IsSuccess\":false")) {
                    System.out.println(result);
                    return null;
                }
                JSONArray array = JSONArray.parseArray(result);
                //将取值的key和value的顺序对应组成map
                List<Map<String, Object>> data = new LinkedList<>();
                array.forEach(a -> {
                    JSONArray arr = (JSONArray) a;
                    Map<String, Object> map = new LinkedHashMap<>((int) (arr.size() / 0.75 + 1));
                    String[] fieldList = fieldKeys.replaceAll(" ", "").split(",");
                    for (int i = 0; i < fieldList.length; i++) {
                        map.put(fieldList[i], arr.get(i));
                    }
                    data.add(map);
                });
                return data;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 一层转换
     */
    public Map<Long, Long> kingdeeUserIdTransition() {
        String formId = "BD_NEWSTAFF"; //
        String fieldKeys = "FSTAFFID,FEmpInfoId";
        return getDataJson(formId, fieldKeys)
                .stream().collect(Collectors.toMap(a -> a.getLong("FSTAFFID"), a -> a.getLong("FEmpInfoId")));
    }

    /**
     * 一层转换找不到数据，就尝试二层转换，
     */
    public Map<Long, Long> kingDeeBusUserIdTransition() {
        Map<Long, Long> jobMap = kingdeeUserIdTransition();
        return getJob().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> jobMap.get(e.getValue())));
    }

    private Map<Long, Long> getJob() {
        String formId = "BD_OPERATOR"; //
        String fieldKeys = "FEntity_FEntryId,FStaffId";
        return getDataJson(formId, fieldKeys, "FName = '张剑'").stream()
                .collect(Collectors.toMap(a -> a.getLong("FEntity_FEntryId"), a -> a.getLong("FStaffId")));
    }

    protected List<JSONObject> getFile(String billType, Collection<Long> ids) {
        String[] fields = new String[]{"FID", "FBillType", "FInterID", "FAttachmentName"
                , "FFileId", "FIsAllowDownload"};
        String where = "FBillType =" + String.format("'%s'", billType);
        where = where + AND + "FInterID in(" + StringUtils.join(ids, ",") + ")";
        return getDataJson("BOS_Attachment", fields, where);
    }


    public Map<String, List<String>> existData(String params, List<String> types) {
        String where = "FOPERATENAME  = '删除' and FINTERID is not null and FDESCRIPTION like '%删除成功%'";
        if (StrUtil.isNotBlank(params))
            where = where + StrPool.C_SPACE + "and" + StrPool.C_SPACE + params;
        if (CollectionUtil.isNotEmpty(types)) {
            String sql = types.stream().map(d -> "'" + d + "'").collect(Collectors.joining(","));
            where = where + StrPool.C_SPACE + "and" + StrPool.C_SPACE + "FOBJECTTYPEID.FID in (" + sql + ")";
        }

        String[] fieldKeys = new String[]{"FINTERID", "FOBJECTTYPEID.FID"};
        List<JSONObject> dataJson = getDataJson("BOS_operateLog", fieldKeys, where);
        return dataJson.stream().collect(Collectors.groupingBy(d -> d.getString("FOBJECTTYPEID.FID"), Collectors.mapping(d -> d.getString("FINTERID"), Collectors.toList())));
    }
//
//    private  Map<String, List<String>> t1(List<String> types){
//        String where = "FOPERATENAME  = '删除' and FINTERID is not null and FDESCRIPTION not like '%删除成功%'";
//        String sql = types.stream().map(d->"'"+d+"'").collect(Collectors.joining(","));
//        where  = where + StrPool.C_SPACE + "and" + StrPool.C_SPACE + "FOBJECTTYPEID.FID in (" +sql+ ")";
//        String[] fieldKeys = new String[]{"FINTERID", "FOBJECTTYPEID.FID"};
//        List<JSONObject> dataJson = getDataJson("BOS_operateLog", fieldKeys, where);
//        Map<String, List<String>> finterid = dataJson.stream().collect(Collectors.groupingBy(d -> d.getString("FOBJECTTYPEID.FID"), Collectors.mapping(d -> d.getString("FINTERID"), Collectors.toList())));
//return  finterid;
//    }
//    private Map<String, List<String>> t2( Map<String, List<String>> ids){
//         Map<String, List<String>> re  = new HashMap<>();
//        for (String s : ids.keySet()) {
//            String where = "FOPERATENAME  = '删除' and FOBJECTTYPEID.FID = '"+s+"' and FINTERID in ("+ ids.get(s).stream().map(d->"'"+d+"'").collect(Collectors.joining(",")) +") and FDESCRIPTION like '%删除成功%'";
//            String[] fieldKeys = new String[]{"FINTERID", "FOBJECTTYPEID.FID"};
//            List<JSONObject> dataJson = getDataJson("BOS_operateLog", fieldKeys, where);
//            List<String> finterid = dataJson.stream().map(d -> d.getString("FINTERID")).collect(Collectors.toList());
//            re.put(s,ids.get(s).stream().filter(d->!finterid.contains(d)).collect(Collectors.toList()));
//        }
//return  re;
//    }
//
//    public static void main(String[] args) {
//        BaseKingDee baseKingDee = new BaseKingDee();
//        Map<String, List<String>> stringListMap = baseKingDee.t1( Arrays.stream(ObjectTypeEnum.values()).map(Enum::name).collect(Collectors.toList()));
//        Map<String, List<String>> stringListMap1 = baseKingDee.t2(stringListMap);
//        System.out.println();
//    }
}
